package com.edu.base.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

import com.edu.base.common.config.Global;

/**
 * 模拟OSS，但存到本地，返回一个对外URl，配合LocalOssController使用
 * 
 */
public class LocalOssUploadUtils {
	 
	
	/*
	 *描述:上传本地储，返回对外的URL地址，地址可配置文件中配置download.path
	 */
	public static String uploadAndGetUrl(MultipartFile uploadfile){
		 
		String fileName=uploadFile(uploadfile,"");
		return  Global.getConfig("download.path")+fileName;
	}
	
	
	/*
	 *描述:上传单个 
	 */
	public static String uploadFile(MultipartFile uploadfile,String path){
		//返回路径信息
		String returnPath = "";
		//获取项目路径
		String realPath =Global.getConfig("upload.path");// ;request.getSession().getServletContext().getRealPath("/");
		//流对象
		InputStream stream = null;
		FileOutputStream fs = null;
		String newName ="";
		try {
				//得到文件名
				String filename=uploadfile.getOriginalFilename();
				String contentType = uploadfile.getContentType();
				int lastIndexOf = filename.lastIndexOf(".");
				newName = IdGen.uuid() + filename.substring(lastIndexOf);
				returnPath += realPath + path + newName + ",";
				//得到读取流
				stream = uploadfile.getInputStream();
				//输出流
				File dirfile= new File(realPath );
				
				if(!dirfile.exists())  
					dirfile.mkdirs();
				File file= new File(realPath +newName);
				fs = new FileOutputStream(file);
				byte[] buffer =new byte[1024*1024];
				int byteread = 0; 
				while ((byteread=stream.read(buffer))!=-1){
					fs.write(buffer,0,byteread);
					fs.flush();
				} 
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("上传失败了！！！");
		}finally{
			try {
				fs.close();
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return newName;
	}
	
	
}
